﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Caching;
using System.Web.Security;
using Widget.Entity;

namespace Widget.Lib
{
    public class Store : IStore
    {
        string locker = "inner";
        ObjectCache StoreCache = MemoryCache.Default;
        string userPrefix = "_user_";
        ChatMessageCollection newMessageStore = new ChatMessageCollection();
        ChatMessageCollection savedMessageStore = new ChatMessageCollection();
        public ChatMessage Add(string key, string user, string contact, string msg, string ip)
        {
            ChatMessage m = new ChatMessage() { FromContact = user, ID = new Random().Next(100000), Message = msg, ToContact = contact, IP = ip };
            newMessageStore.Add(m);
            return m;
        }
        public List<OnLineUser> GetOnlineUser(string role)
        {
            List<OnLineUser> users = StoreCache[userPrefix] as List<OnLineUser>;
            if (users == null)
            {
                users = UserSync();
            }
            //var usr = (from u in users where u.Roles.Contains(role) select u).ToList();
            var usr = (from u in users select u).ToList();
            return usr;
        }
        public List<OnLineUser> CleanSignedOffUser()
        {
            return UserSync();
        }
        public List<OnLineUser> UserSync()
        {
            List<OnLineUser> users = new List<OnLineUser>();
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(60.0);
            foreach (MembershipUser user in Membership.GetAllUsers())
            {
                if (user.IsOnline)
                {
                    OnLineUser u = new OnLineUser() { UserName = user.UserName, UserEmail = user.Email, UpTime = user.LastActivityDate };
                    u.Roles = Roles.GetRolesForUser(user.UserName);
                    users.Add(u);
                }
            }
            lock (locker)
            {
                StoreCache.Add(userPrefix, users, policy);
            }
            return users;
        }
        public List<ChatMessage> GetMessages(string user, string contact)
        {
            var ims = (from m in newMessageStore
                       where m.ToContact == user || m.FromContact == user
                       select m).ToList();
            var sms = StoreCache[user] as List<ChatMessage>;
            if (sms == null) sms = MessageSyncOut(user);
            if (sms != null)
            {
                ims.Union(sms);
            }
            return ims;
        }
        public void CleanUserMessages(string user)
        {
            throw new NotImplementedException();
        }
        void IStore.CleanSignedOffUser()
        {
            throw new NotImplementedException();
        }
        void IStore.UserSync()
        {
            throw new NotImplementedException();
        }
        public ChatMessage SendMessage(string user, string contact, string message, string ip)
        {
            ChatMessage m = new ChatMessage()
            {
                FromContact = user,
                ID = 0,
                IP = ip,
                Message = message,
                ToContact = contact
            };
            newMessageStore.Add(m);

            return m;
        }
        public List<ChatMessage> MessageSyncIn(string user)
        {
            List<ChatMessage> messages = StoreCache[user] as List<ChatMessage>;
            if (messages != null)
            {
                using (Entity.BlankDataClassesDataContext ctx = new Entity.BlankDataClassesDataContext())
                {
                    var msgs = (from m in messages
                                where m.IP != null
                                select new content_Chat()
                                {
                                    FromUser = m.FromContact,
                                    Message = m.Message,
                                    MessageName = Guid.NewGuid().ToString(),
                                    IP = m.IP,
                                    SentDate = DateTime.Now,
                                    Source = m.IP,
                                    ToUser = m.ToContact
                                });
                    ctx.content_Chats.InsertAllOnSubmit(msgs);
                    ctx.SubmitChanges();
                }
            }
            return messages;
        }
        public List<ChatMessage> MessageSyncOut(string user)
        {
            //int pageSize = 10;
            //int pageIndex = 1;
            List<ChatMessage> messages = new List<ChatMessage>();
            using (Entity.BlankDataClassesDataContext ctx = new Entity.BlankDataClassesDataContext())
            {
                var msgs = (from m in ctx.content_Chats
                            where m.FromUser == user || m.ToUser == user
                            select new ChatMessage() { FromContact = m.FromUser, ToContact = m.ToUser, Message = m.Message, ID = m.MessageID.Value });
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(60.0);
                messages = msgs.ToList();
                StoreCache.Add(user, messages, policy);
            }
            return messages;
        }


        public ChatMessageCollection Get(string key)
        {
            throw new NotImplementedException();
        }

        public void Set(string key, ChatMessageCollection message)
        {
            throw new NotImplementedException();
        }
    }
}

